package com.bi.dataDmTrans.service;

import dm.jdbc.filter.stat.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
//import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
@Slf4j
public class TokenService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${third.foreign.token.path}")
    private String tokenPath;

    @Value("${third.foreign.gettoken.url}")
    private String getTokenUrl;

    public String getToken(String url, Object requestPayload) {

        Path path = Paths.get(tokenPath);
        String data = "";

        try {
            if (Files.exists(path)) {
                data = Files.readAllLines(path).get(0).toString();
                log.info("Token exists: " + data);
            }

            if (data.isEmpty()) {
                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json");

                HttpEntity<Object> entity = new HttpEntity<>(requestPayload, headers);

                ResponseEntity<String> response = restTemplate.exchange(getTokenUrl, HttpMethod.POST, entity, String.class);

                // 解析响应体为 JSON 对象
                JSONObject json = new JSONObject(response.getBody());

                // 检查目录是否存在，如果不存在，就创建它
                Files.createDirectories(path.getParent());

                // 将字符串写入文件
                Files.write(path, json.getString("access_token").getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public void updateToken() {

        Path path = Paths.get(tokenPath);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        HttpEntity<Object> entity = new HttpEntity<>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange(getTokenUrl, HttpMethod.POST, entity, String.class);

        // 解析响应体为 JSON 对象
        JSONObject json = new JSONObject(response.getBody());

        // 将字符串写入文件
        try {
            Files.write(path, json.getString("access_token").getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
